package com.lagou.service.com.lagou.zookeeper;

import org.I0Itec.zkclient.ZkClient;


public class ZooKeeperServiceRegistry  implements ServiceRegistry {

    private final static String ZK_REGISTRY_PATH = "/zk-rpc-server";

    private static ZkClient zkClient;

    public ZooKeeperServiceRegistry(String zkAddress) {
        if(zkClient == null){
            // 创建 ZooKeeper 客户端
            zkClient = new ZkClient(zkAddress);
            System.out.println("connect zookeeper");
        }
    }

    @Override
    public void register(String serviceName, String serviceAddress) {
        // 创建 registry 节点（持久）
        String registryPath = ZK_REGISTRY_PATH;
        if (!zkClient.exists(registryPath)) {
            zkClient.createPersistent(registryPath);
            System.out.println("create registry node: "+ registryPath);
        }
        // 创建 service 节点（持久）
        String servicePath = registryPath + "/" + serviceName;
        if (!zkClient.exists(servicePath)) {
            zkClient.createPersistent(servicePath);
            System.out.println("create service node: " + servicePath);
        }
        // 创建 address 节点（临时）
        String addressPath = servicePath + "/address-";
        String addressNode = zkClient.createEphemeralSequential(addressPath, serviceAddress);
        System.out.println("create address node: " + addressNode);
    }

    @Override
    public void addServiceResponseInfo(String serviceName, String serviceAddress, Long endTime, Long currentTime) {

        // 创建 registry 节点（持久）
        String registryPath = ZK_REGISTRY_PATH;
        if (!zkClient.exists(registryPath)) {
            zkClient.createPersistent(registryPath);
            System.out.println("create registry node: "+ registryPath);
        }
        // 创建 service 节点（持久）
        String servicePath = registryPath + "/" + serviceName+"-response";
        if (!zkClient.exists(servicePath)) {
            zkClient.createPersistent(servicePath);
            System.out.println("create service node: " + servicePath);
        }

        // 创建 response 节点（持久）
        String responsePath = servicePath + "/" + serviceAddress;
        if (!zkClient.exists(responsePath)) {
            zkClient.createPersistent(responsePath,endTime+":"+currentTime);
            System.out.println("create response node: " + responsePath);
        }else{
            //获取节点内容
            Object o = zkClient.readData(responsePath);
            System.out.println("更新前数据---------------->:"+o);

            zkClient.writeData(responsePath,endTime+":"+currentTime);

            //获取节点内容
            Object o2 = zkClient.readData(responsePath);
            System.out.println("更新后数据-------------->:"+o2);
        }
    }
}